from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.db.models import Count, Q, Sum
from django.utils import timezone
from datetime import timedelta
from .models import Story, StoryCategory
from .forms import StoryForm, StoryGenerateForm, StorySearchForm
from user.models import UserActivity, User
from interactive.models import Comment, Like, Favorite, Report, Notification
from .services import AIService

@login_required
def story_list(request):
    # 获取所有分类
    categories = StoryCategory.objects.all().order_by('order')
    
    # 获取当前选中的分类
    category_id = request.GET.get('category')
    search_query = request.GET.get('q', '')
    
    # 基础查询：非草稿的故事
    stories = Story.objects.filter(is_draft=False)
    
    # 按分类筛选
    if category_id:
        try:
            category_id = int(category_id)
            stories = stories.filter(category_id=category_id)
            selected_category = get_object_or_404(StoryCategory, id=category_id)
        except (ValueError, StoryCategory.DoesNotExist):
            selected_category = None
    else:
        selected_category = None
        
    # 搜索功能
    if search_query:
        stories = stories.filter(
            Q(title__icontains=search_query) | 
            Q(content__icontains=search_query) |
            Q(keywords__icontains=search_query)
        )
    
    # 排序
    stories = stories.order_by('-created_at')
    
    # 分页
    paginator = Paginator(stories, 12)  # 每页显示12个故事
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'categories': categories,
        'selected_category': selected_category,
        'search_query': search_query
    }
    
    return render(request, 'story/list.html', context)

@login_required
def story_create(request):
    if request.method == 'POST':
        form = StoryForm(request.POST)
        if form.is_valid():
            story = form.save(commit=False)
            story.author = request.user
            story.save()
            # 记录用户活动
            UserActivity.objects.create(
                user=request.user,
                activity_type='create_story',
                activity_data={'story_id': story.id, 'title': story.title}
            )
            messages.success(request, '故事创建成功！')
            return redirect('story:detail', pk=story.pk)
    else:
        form = StoryForm()
    return render(request, 'story/create.html', {'form': form})

@login_required
def story_edit(request, pk):
    story = get_object_or_404(Story, pk=pk, author=request.user)
    if request.method == 'POST':
        form = StoryForm(request.POST, instance=story)
        if form.is_valid():
            story = form.save()
            # 记录用户活动
            UserActivity.objects.create(
                user=request.user,
                activity_type='edit_story',
                activity_data={'story_id': story.id, 'title': story.title}
            )
            messages.success(request, '故事更新成功！')
            return redirect('story:detail', pk=story.pk)
    else:
        form = StoryForm(instance=story)
    return render(request, 'story/edit.html', {'form': form, 'story': story})

@login_required
def story_detail(request, pk):
    story = get_object_or_404(Story, pk=pk)
    if not story.is_draft or (request.user.is_authenticated and request.user == story.author):
        # 增加浏览量
        story.views += 1
        story.save()
        
        # 获取评论并分页
        comments = story.comments.all().order_by('-created_at')
        paginator = Paginator(comments, 10)  # 每页显示10条评论
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        
        # 检查用户是否已点赞或收藏
        user_liked = Like.objects.filter(user=request.user, story=story).exists()
        user_favorited = Favorite.objects.filter(user=request.user, story=story).exists()
        
        # 记录用户活动
        UserActivity.objects.create(
            user=request.user,
            activity_type='view_story',
            activity_data={'story_id': story.id, 'title': story.title}
        )
        
        context = {
            'story': story,
            'comments': page_obj,
            'user_liked': user_liked,
            'user_favorited': user_favorited
        }
        return render(request, 'story/detail.html', context)
    else:
        messages.error(request, '您没有权限查看此故事。')
        return redirect('story:list')

@login_required
def story_delete(request, pk):
    story = get_object_or_404(Story, pk=pk, author=request.user)
    if request.method == 'POST':
        # 记录用户活动
        UserActivity.objects.create(
            user=request.user,
            activity_type='delete_story',
            activity_data={'story_id': story.id, 'title': story.title}
        )
        story.delete()
        messages.success(request, '故事已删除。')
        return redirect('story:list')
    return render(request, 'story/delete.html', {'story': story})

@login_required
def story_generate(request):
    if request.method == 'POST':
        form = StoryGenerateForm(request.POST)
        if form.is_valid():
            try:
                # 获取分类对象，用于传递给AI服务
                category = form.cleaned_data['category']
                category_name = category.name if category else ""
                
                # 使用 AI 服务生成故事
                generated_story = AIService.generate_story(
                    title=form.cleaned_data['title'],
                    category=category_name,  # 使用分类名称
                    keywords=form.cleaned_data['keywords'],
                    length=form.cleaned_data['length'],
                    style=form.cleaned_data['style']
                )
                
                # 记录用户活动
                UserActivity.objects.create(
                    user=request.user,
                    activity_type='generate_story',
                    activity_data={'title': generated_story["title"]}
                )
                
                # 将分类信息添加到上下文
                return render(request, 'story/generate.html', {
                    'form': form,
                    'generated_story': generated_story,
                    'selected_category_id': category.id if category else None,
                    'selected_category_name': category_name
                })
            except Exception as e:
                messages.error(request, f'故事生成过程中出现错误: {str(e)}')
                return render(request, 'story/generate.html', {'form': form})
    else:
        form = StoryGenerateForm()
    
    return render(request, 'story/generate.html', {'form': form})

@login_required
@require_POST
def story_comment(request, pk):
    story = get_object_or_404(Story, pk=pk)
    content = request.POST.get('content')
    if content:
        Comment.objects.create(story=story, user=request.user, content=content)
        messages.success(request, '评论发表成功')
    return redirect('story:detail', pk=pk)

@login_required
@require_POST
def story_like(request, pk):
    story = get_object_or_404(Story, pk=pk)
    like, created = Like.objects.get_or_create(story=story, user=request.user)
    
    # 更新实际的点赞数
    if created:
        # 如果是创建了新的点赞，增加点赞数
        story.likes += 1
    else:
        # 如果是取消点赞，减少点赞数（但确保不会小于0）
        like.delete()
        story.likes = max(0, story.likes - 1)
    
    # 保存更新后的点赞数
    story.save(update_fields=['likes'])
    
    # 通知和活动记录
    if created and request.user != story.author:
        Notification.objects.create(
            recipient=story.author,
            sender=request.user,
            notification_type='like',
            content=f'{request.user.username} 点赞了你的故事《{story.title}》',
            related_story=story
        )
    
    # 记录用户活动
    if created:
        UserActivity.objects.create(
            user=request.user,
            activity_type='like_story',
            activity_data={'story_id': story.id, 'title': story.title}
        )
    
    return JsonResponse({
        'status': 'success',
        'liked': created,
        'likes_count': story.likes
    })

@login_required
@require_POST
def story_favorite(request, pk):
    story = get_object_or_404(Story, pk=pk)
    favorite, created = Favorite.objects.get_or_create(story=story, user=request.user)
    
    if not created:
        favorite.delete()
    
    # 通知和活动记录
    if created and request.user != story.author:
        Notification.objects.create(
            recipient=story.author,
            sender=request.user,
            notification_type='favorite',
            content=f'{request.user.username} 收藏了你的故事《{story.title}》',
            related_story=story
        )
    
    # 记录用户活动
    if created:
        UserActivity.objects.create(
            user=request.user,
            activity_type='favorite_story',
            activity_data={'story_id': story.id, 'title': story.title}
        )
    
    return JsonResponse({
        'status': 'success',
        'favorited': created
    })

@login_required
@require_POST
def story_report(request, pk):
    story = get_object_or_404(Story, pk=pk)
    report_type = request.POST.get('report_type')
    description = request.POST.get('description')
    if report_type and description:
        Report.objects.create(
            story=story,
            reporter=request.user,
            report_type=report_type,
            description=description
        )
        messages.success(request, '举报已提交，我们会尽快处理')
    return redirect('story:detail', pk=pk)

@login_required
def save_generated_story(request):
    """
    保存从AI生成的故事
    """
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        category_id = request.POST.get('category')
        keywords = request.POST.get('keywords')
        
        # 创建新的故事对象
        story = Story(
            title=title,
            content=content,
            keywords=keywords,
            author=request.user,
            is_draft=False
        )
        
        # 设置分类
        if category_id:
            try:
                category = StoryCategory.objects.get(id=category_id)
                story.category = category
            except (StoryCategory.DoesNotExist, ValueError):
                # 如果找不到分类或ID无效，尝试根据名称找到或创建分类
                category_name = request.POST.get('category_name', '')
                if category_name:
                    category, created = StoryCategory.objects.get_or_create(
                        name=category_name,
                        defaults={'description': f'由系统自动创建的"{category_name}"分类'}
                    )
                    story.category = category
            
        story.save()
        
        # 记录用户活动
        UserActivity.objects.create(
            user=request.user,
            activity_type='save_generated_story',
            activity_data={'story_id': story.id, 'title': story.title}
        )
        
        messages.success(request, 'AI生成的故事已成功保存！')
        return redirect('story:detail', pk=story.pk)
    
    # 如果不是POST请求，重定向到生成页面
    return redirect('story:generate')

def ranking_list(request):
    """
    故事排行榜页面
    """
    ranking_type = request.GET.get('type', 'likes')
    time_range = request.GET.get('time', 'all')
    category_id = request.GET.get('category', '')
    
    # 基础查询集：只查询已发布的故事
    stories = Story.objects.filter(is_draft=False)
    
    # 根据时间范围筛选
    if time_range == 'day':
        start_time = timezone.now() - timedelta(days=1)
        stories = stories.filter(created_at__gte=start_time)
        time_title = "日榜"
    elif time_range == 'week':
        start_time = timezone.now() - timedelta(days=7)
        stories = stories.filter(created_at__gte=start_time)
        time_title = "周榜"
    elif time_range == 'month':
        start_time = timezone.now() - timedelta(days=30)
        stories = stories.filter(created_at__gte=start_time)
        time_title = "月榜"
    else:
        time_title = "总榜"
    
    # 根据分类筛选
    if category_id:
        try:
            category = StoryCategory.objects.get(id=category_id)
            stories = stories.filter(category=category)
            category_title = f"{category.name}"
        except (StoryCategory.DoesNotExist, ValueError):
            category_title = ""
    else:
        category_title = ""
    
    # 根据排名类型排序
    if ranking_type == 'views':
        stories = stories.order_by('-views')
        type_title = "阅读量"
    elif ranking_type == 'comments':
        # 通过关联计数，获取评论数最多的故事
        stories = stories.annotate(comments_count=Count('comments')).order_by('-comments_count')
        type_title = "评论数"
    else:  # 默认按点赞数排序
        stories = stories.order_by('-likes')
        type_title = "点赞数"
    
    # 获取前50个结果
    stories = stories[:50]
    
    # 为结果添加排名
    ranked_stories = []
    for i, story in enumerate(stories, 1):
        story.rank = i
        ranked_stories.append(story)
    
    # 构建页面标题
    if category_title:
        title = f"{category_title} · {time_title} · {type_title}排行"
    else:
        title = f"{time_title} · {type_title}排行"
    
    # 获取所有分类以供筛选
    categories = StoryCategory.objects.all().order_by('order')
    
    context = {
        'stories': ranked_stories,
        'ranking_type': ranking_type,
        'time_range': time_range,
        'categories': categories,
        'selected_category': category_id,
        'title': title
    }
    
    return render(request, 'story/ranking.html', context)

def home(request):
    """网站首页，显示最新故事和热门故事，提供全站搜索"""
    search_query = request.GET.get('q', '')
    
    # 基础查询：非草稿的故事
    latest_stories = Story.objects.filter(is_draft=False)
    popular_stories = Story.objects.filter(is_draft=False)
    
    # 搜索功能
    if search_query:
        search_results = Story.objects.filter(
            is_draft=False
        ).filter(
            Q(title__icontains=search_query) | 
            Q(content__icontains=search_query) |
            Q(keywords__icontains=search_query) |
            Q(author__username__icontains=search_query)
        ).order_by('-created_at')
        
        # 分页
        paginator = Paginator(search_results, 12)
        page_number = request.GET.get('page')
        search_page = paginator.get_page(page_number)
        
        context = {
            'search_query': search_query,
            'search_results': search_page,
            'is_search': True
        }
        return render(request, 'home/search_results.html', context)
    
    # 获取最新故事（最近7天内发布的）
    latest_stories = latest_stories.order_by('-created_at')[:6]
    
    # 获取热门故事（按照点赞数和浏览量排序）
    popular_stories = popular_stories.order_by('-likes', '-views')[:6]
    
    # 获取所有分类以供导航
    categories = StoryCategory.objects.all().order_by('order')
    
    # 获取系统统计数据
    user_count = User.objects.count()
    story_count = Story.objects.filter(is_draft=False).count()
    view_count = Story.objects.filter(is_draft=False).aggregate(total_views=Sum('views'))['total_views'] or 0
    ai_story_count = 150  # 设置一个估计值或从其他地方获取
    
    context = {
        'latest_stories': latest_stories,
        'popular_stories': popular_stories,
        'categories': categories,
        'user_count': user_count,
        'story_count': story_count,
        'view_count': view_count,
        'ai_story_count': ai_story_count
    }
    
    return render(request, 'home.html', context)
